package com.xingkeduo.business.order.remote;

import com.alibaba.fastjson.JSON;
import com.xingkeduo.business.order.remote.feign.WordPadFeignService;
import com.xingkeduo.dto.BatchLockStockParam;
import com.xingkeduo.dto.enums.StockStatusEnum;
import com.xingkeduo.pojo.table.Order;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chi  2019-03-13 11:10
 **/
@Service
@Slf4j
public class InventoryRemoteService {

    @Resource
    private WordPadFeignService wordPadFeignService;

    /**
     * 锁库存
     * @param stockId
     * @param stockStatusEnum
     * @param order
     */
    public boolean lockInventory(String stockId, StockStatusEnum stockStatusEnum, Order order) {   //加 店铺id， 判断：  stockId 1，创建订单，2，改约 传 其他不传
        log.info("lockInventory:{}    :{},{},{},{},{}", stockId, order.getOrderNo(), stockStatusEnum, order.getWaitingLineNo(), order.getUserHeadUrl(),order.getStoreId());
        if(StringUtils.isBlank(stockId)){
            return false;
        }
        try {
            String lineNo = StringUtils.isNotBlank(order.getWaitingLineNo()) ? order.getWaitingLineNo() : "";

            ResponseUtils responseUtils = null;
            if(stockId.contains(",")){
                String[] split = stockId.split(",");
                List<String> stringList = Arrays.asList(split);
                List<BatchLockStockParam> batchLockStockParams = stringList.stream().map(s -> {
                    BatchLockStockParam batchLockStockParam = new BatchLockStockParam();
                    batchLockStockParam
                            .setStockId(Long.valueOf(s))
                            .setOrderNo(Long.valueOf(order.getOrderNo()))
                            .setStatus(stockStatusEnum.getValue())
                            .setLineNo(order.getWaitingLineNo())
                            .setUserPath(order.getUserHeadUrl())
                            .setStoreId(Long.valueOf(order.getStoreId()));
                    return batchLockStockParam;
                }).collect(Collectors.toList());
                responseUtils = wordPadFeignService.batchLockStockBystockId(batchLockStockParams);

            }else {
                responseUtils = wordPadFeignService.lockStockBystockId(Long.valueOf(stockId), order.getOrderNo(), stockStatusEnum.getValue(), lineNo, order.getUserHeadUrl(),Long.valueOf(order.getStoreId()));
            }

            log.info("lockInventory response:{}", JSON.toJSONString(responseUtils));
            return responseUtils.success();

        } catch (Exception e) {
            log.error("lockInventory锁定库存失败:{}",e);
        }
        return false;
    }


    /**
     * 更新库存
     * @param stockStatusEnum
     * @param order
     */
    public boolean updateInventory(StockStatusEnum stockStatusEnum, Order order) {   //加 店铺id， 判断：  stockId 1，创建订单，2，改约 传 其他不传
        log.info("lock updateInventory:{}    :{},{},{},{},{}", order.getOrderNo(), stockStatusEnum, order.getWaitingLineNo(), order.getUserHeadUrl(),order.getStoreId());
        try {
            String lineNo = StringUtils.isNotBlank(order.getWaitingLineNo()) ? order.getWaitingLineNo() : "";

            ResponseUtils responseUtils = null;
            log.info("lock updateInventory sotckId:{}", order.getAppointmentId());
            if(StringUtils.isNotBlank(order.getAppointmentId()) && order.getAppointmentId().contains(",")){
                String[] split = order.getAppointmentId().split(",");
                List<String> stringList = Arrays.asList(split);
                List<BatchLockStockParam> batchLockStockParams = stringList.stream().map(s -> {
                    BatchLockStockParam batchLockStockParam = new BatchLockStockParam();
                    batchLockStockParam
                            .setOrderNo(Long.valueOf(order.getOrderNo()))
                            .setStatus(stockStatusEnum.getValue())
                            .setLineNo(order.getWaitingLineNo())
                            .setUserPath(order.getUserHeadUrl())
                            .setStoreId(Long.valueOf(order.getStoreId()));
                    return batchLockStockParam;
                }).collect(Collectors.toList());

                log.info("lock updateInventory param:{}", JSON.toJSONString(batchLockStockParams));
                responseUtils = wordPadFeignService.batchLockStockBystockId(batchLockStockParams);

            }else {
                responseUtils = wordPadFeignService.lockStockBystockId(null, order.getOrderNo(), stockStatusEnum.getValue(), lineNo, order.getUserHeadUrl(),Long.valueOf(order.getStoreId()));
            }

            log.info("lock updateInventory response:{}", JSON.toJSONString(responseUtils));
            return responseUtils.success();

        } catch (Exception e) {
            log.error("lock updateInventory锁定库存失败:{}",e);
        }
        return false;
    }


    /**
     * 解锁库存
     * @param order
     */
    public boolean unlockInventory(Order order) {//订单号，和店铺id
        if(order ==null || StringUtils.isBlank(order.getOrderNo())){
            return true;
        }
        try {

            log.info("lock解锁库存:orderNo{}", order.getOrderNo());
            log.info("lock解锁库存:storeId{}", order.getStoreId());

            ResponseUtils responseUtils = null;
            log.info("lock解锁库存 sotckId:{}", order.getAppointmentId());
            if(StringUtils.isNotBlank(order.getAppointmentId()) && order.getAppointmentId().contains(",")){
                String[] split = order.getAppointmentId().split(",");
                List<String> stringList = Arrays.asList(split);
                List<BatchLockStockParam> batchLockStockParams = stringList.stream().map(s -> {
                    BatchLockStockParam batchLockStockParam = new BatchLockStockParam();
                    batchLockStockParam
                            .setOrderNo(Long.valueOf(order.getOrderNo()))
                            .setStoreId(Long.valueOf(order.getStoreId()));
                    return batchLockStockParam;
                }).collect(Collectors.toList());
                responseUtils = wordPadFeignService.batchUnlockStockBystockId(batchLockStockParams);

            }else {
                responseUtils = wordPadFeignService.unlockStockBystockId(order.getOrderNo(), Long.valueOf(order.getStoreId()));
            }

            log.info("lock解锁库存返回:{}", JSON.toJSONString(responseUtils));
            return responseUtils.success();
        } catch (NumberFormatException e) {
            log.error("lock解锁库存失败:{}",e);
        }
        return false;
    }


    /**
     * 库存改约
     * @param stockId
     * @param stockStatusEnum
     * @param order
     * @return
     */
    public boolean changeInventory(String stockId,StockStatusEnum stockStatusEnum, Order order) {//订单号，和店铺id
        if(order ==null || StringUtils.isBlank(order.getOrderNo())){
            return true;
        }
        try {
            log.info("lock改约库存:orderNo{}", order.getOrderNo());
            log.info("lock改约库存:storeId{}", order.getStoreId());

            ResponseUtils responseUtils = null;
            log.info("lock改约库存 sotckId:{}", stockId);
            if(stockId.contains(",")){
                /*String[] split = stockId.split(",");
                List<String> stringList = Arrays.asList(split);
                List<BatchLockStockParam> batchLockStockParams = stringList.stream().map(s -> {
                    BatchLockStockParam batchLockStockParam = new BatchLockStockParam();
                    batchLockStockParam
                            .setStockId(Long.valueOf(s))
                            .setOrderNo(Long.valueOf(order.getOrderNo()))
                            .setStatus(stockStatusEnum.getValue())
                            .setLineNo(order.getWaitingLineNo())
                            .setUserPath(order.getUserHeadUrl())
                            .setStoreId(Long.valueOf(order.getStoreId()));
                    return batchLockStockParam;
                }).collect(Collectors.toList());
                responseUtils = wordPadFeignService.batchLockStockBystockId(batchLockStockParams);*/


                unlockInventory(order);
                boolean b = lockInventory(stockId, StockStatusEnum.WAIT_FOR_SERVICE, order);
                return b;

            }else {
                responseUtils = wordPadFeignService.changeStockBystockIdAndorderNo(Long.valueOf(stockId), order.getOrderNo(), stockStatusEnum.getValue(),Long.valueOf(order.getStoreId()),order.getWaitingLineNo());
            }

            log.info("lock改约库存返回:{}", JSON.toJSONString(responseUtils));
            return responseUtils.success();
        } catch (NumberFormatException e) {
            log.error("lock改约库存失败:{}",e);
        }
        return false;
    }

}
